from Customer.db_connector import DBUtils
import time


class TransactionManager:
    def __init__(self):
        self.db = DBUtils()
        self.db.connect()
        print("数据库连接已建立")

    def __del__(self):
        if hasattr(self, 'db') and self.db.connection.is_connected():
            self.db.disconnect()
            print("数据库连接已关闭")

    def _execute_transaction(self, card_id, amount, remark, trans_type):
        """通用交易执行方法（修复了交易类型识别问题）"""
        try:
            # 根据交易类型正确设置金额符号
            is_deposit = (trans_type == '存款')
            amount_signed = amount if is_deposit else -amount

            # 更新余额
            update_query = """
            UPDATE cardInfo 
            SET balance = balance + %s 
            WHERE cardID = %s
            """
            self.db.execute_query(update_query, (amount_signed, card_id), fetch=False)

            # 记录交易（使用交易类型区分）
            trade_id = self._generate_trade_id()
            insert_query = """
            INSERT INTO tradeInfo 
            (cardID, tradeDate, tradeType, transactionID, tradeMoney, remark)
            VALUES (%s, NOW(), %s, %s, %s, %s)
            """
            # 存入金额为正，取出金额为负
            trade_amount = amount if is_deposit else -amount

            self.db.execute_query(
                insert_query,
                (card_id, trans_type, trade_id, trade_amount, remark),
                fetch=False
            )

            print(f"交易成功: {trans_type} {amount} 元，卡号 {card_id}")
            return True
        except Exception as e:
            print(f"交易失败({trans_type}): {e}")
            return False

    def deposit(self, card_id, amount, remark=None):
        """存款业务"""
        if not isinstance(amount, (int, float)) or amount <= 0:
            print("错误: 存款金额必须为正数")
            return False

        try:
            self.db.connection.start_transaction()

            # 检查银行卡状态（使用FOR UPDATE锁定行）
            check_query = """
            SELECT IsReportLoss 
            FROM cardInfo 
            WHERE cardID = %s FOR UPDATE
            """
            card_info = self.db.execute_query(check_query, (card_id,))

            if not card_info:
                print("错误: 银行卡不存在")
                self.db.connection.rollback()
                return False

            if card_info[0]['IsReportLoss'] == '是':
                print("错误: 银行卡已挂失")
                self.db.connection.rollback()
                return False

            # 执行存款操作
            success = self._execute_transaction(card_id, amount, remark, '存款')

            if success:
                self.db.connection.commit()
            else:
                self.db.connection.rollback()

            return success
        except Exception as e:
            self.db.connection.rollback()
            print(f"存款失败: {e}")
            return False

    def withdraw(self, card_id, amount, password, remark=None):
        """取款业务"""
        if not isinstance(amount, (int, float)) or amount <= 0:
            print("错误: 取款金额必须为正数")
            return False

        try:
            self.db.connection.start_transaction()

            # 验证密码和余额（使用FOR UPDATE锁定行）
            card_query = """
            SELECT balance, pass, IsReportLoss 
            FROM cardInfo 
            WHERE cardID = %s FOR UPDATE
            """
            card_info = self.db.execute_query(card_query, (card_id,))

            if not card_info:
                print("错误: 银行卡不存在")
                self.db.connection.rollback()
                return False

            if card_info[0]['IsReportLoss'] == '是':
                print("错误: 银行卡已挂失")
                self.db.connection.rollback()
                return False

            if card_info[0]['pass'] != password:
                print("错误: 密码不正确")
                self.db.connection.rollback()
                return False

            if card_info[0]['balance'] < amount:
                print("错误: 余额不足")
                self.db.connection.rollback()
                return False

            # 执行取款操作
            success = self._execute_transaction(card_id, amount, remark, '取款')

            if success:
                self.db.connection.commit()
            else:
                self.db.connection.rollback()

            return success
        except Exception as e:
            self.db.connection.rollback()
            print(f"取款失败: {e}")
            return False

    def _generate_trade_id(self):
        """生成交易流水号"""
        return f"TR{int(time.time() * 1000)}"